package com.future.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.future.pojo.*;
import com.future.service.MusicService;
import com.future.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/music")
public class MusicController {

    static Logger logger = Logger.getLogger(MusicController.class);
    @Autowired
    private MusicService musicService;


    @Autowired
    private UserService userService;

    //创建Judge实体类
    Judge judge = new Judge();


    @ApiOperation(value = "查询所有音乐")
    @GetMapping("/allMusic")

    public String queryAllMusic(Model model, Integer page) {
        //初始化页数
        if (page == null) {
            page = 1;
        }
        //总页数
        int count = musicService.countMusic();
        int sumPage = 0;
        if (count % 10 != 0) {
            sumPage = count / 10 + 1;
        } else {
            sumPage = count / 10;
        }
        //获取指定页的数据
        List<Musics> list = musicService.queryAllMusic((page) * 10 - 10, 10);
        //传递参数
        model.addAttribute("page", page);
        model.addAttribute("sumPage", sumPage);
        model.addAttribute("Musics", list);
        return "L-html/L-homepage/L-allsonglist.html";
    }


    @ApiOperation(value = "查询所有歌手")
    @GetMapping("/queryAllSinger")
    public String queryAllSinger(Model model, Integer page) {
        //初始化页数
        if (page == null) {
            page = 1;
        }
        //获取记录条数
        int count = musicService.countSinger();
        int sumPage = 0;
        //获取总页数
        if (count % 10 != 0) {
            sumPage = count / 10 + 1;
        } else {
            sumPage = count / 10;
        }
        //查询每页数据
        List<Users> list = musicService.queryAllSinger(page * 10 - 10, 10);
        model.addAttribute("page", page + 1);
        model.addAttribute("sumPage", sumPage);
        model.addAttribute("Singers", list);
        return "/L-html/L-homepage/L-allSingers.html";
    }


    @ApiOperation(value = "根据ID查找音乐和专辑信息")
    @GetMapping("/queryByIdAlbmusic")
    public String queryByIdAlbmusic(int mcId, Model model, HttpSession session) {
        Users user = (Users)session.getAttribute("USER");
        //音乐热度+1
        musicService.addHotMusic(mcId);
        //查找专辑歌曲信息
        Albmusic albmusic = musicService.queryByIdAlbmusic(mcId);
        List<Albmusic> list = new ArrayList<>();
        list.add(albmusic);
        if (user != null) {
            System.out.println(list.get(0).getMcName());
            //判断歌曲是否已经添加我喜欢
            int num = userService.checkLike(list.get(0).getMcName(), user.getUserId());
            System.out.println(num);
            model.addAttribute("isLike", num);
        }
        model.addAttribute("Musics", list);
        return "/L-html/L-homepage/L-lyric.html";
    }


    @ApiOperation(value = "歌曲上一首")
    @RequestMapping("/queryup")
    public String queryup(int mcId, Model model, HttpSession session) {
        Users user = (Users)session.getAttribute("USER");
        //音乐热度+1
        musicService.addHotMusic(mcId);
        //获取第一曲的歌曲id
        int one = musicService.musicFirst();
        int n = mcId;
        while (musicService.queryByIdAlbmusic(n - 1) == null) {
            //判断是否已经是第一曲
            if (n >= one) {
                n--;
            } else {
                break;
            }
        }
        if (n >= one) {
            Albmusic albmusic = musicService.queryByIdAlbmusic(n - 1);
            List<Albmusic> list = new ArrayList<>();
            list.add(albmusic);
            if (user != null) {
                System.out.println(list.get(0).getMcName());
                int num = userService.checkLike(list.get(0).getMcName(), user.getUserId());
                System.out.println(num);
                model.addAttribute("isLike", num);
            }

            model.addAttribute("Musics", list);
            return "/L-html/L-homepage/L-lyric.html";
        } else {
            model.addAttribute("msg", "歌曲到头了");
            //如果是第一曲就返回第一曲界面
            Albmusic albmusic = musicService.queryByIdAlbmusic(one);
            List<Albmusic> list = new ArrayList<>();
            list.add(albmusic);
            if (user != null) {
                System.out.println(list.get(0).getMcName());
                int num = userService.checkLike(list.get(0).getMcName(), user.getUserId());
                System.out.println(num);
                model.addAttribute("isLike", num);
            }
            model.addAttribute("Musics", list);
            return "/L-html/L-homepage/L-lyric.html";
        }
    }


    @ApiOperation(value = "歌曲下一首")
    @RequestMapping("/querydown")
    public String querydown(int mcId, Model model, HttpSession session) {
        Users user = (Users)session.getAttribute("USER");
        //音乐热度+1
        musicService.addHotMusic(mcId);
        //获取最后一曲的歌曲id
        int last = musicService.musicFinally();
        int n = mcId;
        //判断是否是最后一曲
        while (musicService.queryByIdAlbmusic(n + 1) == null) {
            if (n <= last) {
                n++;
            } else {
                System.out.println("到头了");
                break;
            }
        }
        if (n <= last) {
            Albmusic albmusic = musicService.queryByIdAlbmusic(n + 1);
            List<Albmusic> list = new ArrayList<>();
            list.add(albmusic);
            if (user != null) {
                System.out.println(list.get(0).getMcName());
                int num = userService.checkLike(list.get(0).getMcName(), user.getUserId());
                System.out.println(num);
                model.addAttribute("isLike", num);
            }
            model.addAttribute("Musics", list);
            return "/L-html/L-homepage/L-lyric.html";
        } else {
            model.addAttribute("msg", "歌曲到头了");
            Albmusic albmusic = musicService.queryByIdAlbmusic(last);
            List<Albmusic> list = new ArrayList<>();
            list.add(albmusic);
            if (user != null) {
                System.out.println(list.get(0).getMcName());
                int num = userService.checkLike(list.get(0).getMcName(), user.getUserId());
                System.out.println(num);
                model.addAttribute("isLike", num);
            }
            model.addAttribute("Musics", list);
            return "/L-html/L-homepage/L-lyric.html";
        }
    }


    @ApiOperation(value = "根据歌名模糊查询")
    @GetMapping("/queryByNameMusic")                       //测试通过
    public String queryByNameMusic(String queryMusicName, Model model,Integer page) {
        //第一次进入页面page为null，将page赋值为1
        if(page==null){
            page=1;
        }
        //得到数据总数，算出总页数
        int sumPage = 1;

        List<Musics> list = musicService.queryByNameMusic(queryMusicName,page*10-10,10);
        model.addAttribute("page",page);
        model.addAttribute("sumPage",sumPage);
        model.addAttribute("Musics", list);
        return "/L-html/L-homepage/L-search.html";
    }

    @ApiOperation(value = "根据热度排名")
    @GetMapping("/HotMusic")
    @ResponseBody
    //获取推荐歌曲
    public String HotMusic(Model model) {
        List<Musics> list = musicService.HotMusic();
        model.addAttribute("Musics", list);
        return "list";
    }


    @ApiOperation(value = "获取一个人的所有歌单")
    @GetMapping("/userMusiclist")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    })
    @ResponseBody
    public String userMusiclist(Model model, int userId) {
        //根据Id获取个人歌单
        List<Musiclist> list = musicService.userMusiclist(userId);
        model.addAttribute("Musics", list);
        return "list";
    }


    @ApiOperation(value = "查询一个歌单中的所有歌曲")
    @GetMapping("/queryOnemclist")
    public String queryOnemclist(Model model, int userId, String mclsName) {
        //查询歌单中的歌曲
        List<Musiclistmusic> list = musicService.queryOnemclist(userId, mclsName);
        model.addAttribute("Musiclistmusic", list);
        System.out.println(list);
        return "redirect:/music/allMusic";
    }



    @ApiOperation(value = "向歌单里面添加歌曲")
    @PostMapping("/addMusictolist")
    @ResponseBody
    public Judge addMusictolist(int userId, String mclsName, String mcName, Model model) {
        int result = musicService.addMusictolist(userId, mclsName, mcName);
        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("添加成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("添加失败！");
        }
        return judge;
    }


    @ApiOperation(value = "向我喜欢歌单里面添加歌曲")
    @RequestMapping("/addMusictoLovelist")
    @ResponseBody
    public Judge addMusictoLovelist(Musiclist musiclist, String mcName, HttpSession session) {
        //获取登录的ID
        Users user = (Users)session.getAttribute("USER");
        //检查是否已经加入到我喜欢
        int num = userService.checkLike(mcName, user.getUserId());
        if (num == 1) {
            int nums = musicService.deleteLike(mcName, user.getUserId());
            judge.setStatusCode(0);
            judge.setInfo("取消收藏！");
        } else {
            musiclist.setUserId(user.getUserId());
            //添加我喜欢数据
            int result = musicService.addMusictoLovelist(musiclist);
            if (result > 0) {
                judge.setStatusCode(1);
                judge.setInfo("添加成功！");
            } else {
                judge.setStatusCode(-1);
                judge.setInfo("添加失败！");
            }
        }
        return judge;
    }


    @ApiOperation(value = "下载歌曲")
    @RequestMapping("/addMusicToDownlist")
    @ResponseBody
    public Judge addMusicToDownlist(HttpServletResponse response, Musiclist musiclist, String mcName, String mcLoaddele, Model model) {
        String load = mcLoaddele;
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";
        //获取文件路径
        String filePath = load;
        String bucketName = "jianglin-bucket";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, filePath);
        // 读去Object内容  返回
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        try {
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "utf-8"));
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        ossClient.shutdown();
        musiclist.setMclsName(mcName);
        musiclist.setUserId(1);
        int result = musicService.addMusicToDownlist(musiclist);

        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("下载成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("下载失败！");
        }
        return judge;
    }


    @ApiOperation(value = "歌单里面删除一个歌曲")
    @PostMapping("/deletelistMusic")
    @ResponseBody
    public Judge deletelistMusic(int mclsId, Model model) {
        int result = musicService.deletelistMusic(mclsId);
        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("删除成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("删除失败！");
        }
        return judge;
    }


    @ApiOperation(value = "删除一个歌单")
    @PostMapping("/deleteMusiclist")
    @ResponseBody
    public Judge deleteMusiclist(int userId, String mclsName, Model model) {
        //通过用户Id和歌单名字删除一个歌单数据
        int result = musicService.deleteMusiclist(userId, mclsName);
        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("删除成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("删除失败！");
        }
        return judge;
    }



    @ApiOperation(value = "新建一个专辑")
    @PostMapping("/addAlbum")
    @ResponseBody
    public Judge addAlbum(Album album, Model model, @RequestParam("file") CommonsMultipartFile filex) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";
        String uploadFileName = filex.getOriginalFilename();
        //获取文件路径
        String fileName = uploadFileName;
        String bucketName = "jianglin-bucket";
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        if (suffixName == ".jpg" || suffixName == ".png" || suffixName == ".jpeg" || suffixName == ".JPG" || suffixName == ".PNG" || suffixName == ".JPNG") {

            // 生成上传文件名
            String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
            String objectName = sdf.format(new Date()) + "/" + finalFileName;
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {
                ossClient.putObject(bucketName, objectName, filex.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 设置URL过期时间。
            Date expiration = new Date(System.currentTimeMillis() + 999999999 * 1000000000);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            ossClient.shutdown();
            System.out.println(url.toString());
            album.setAlbImgload(url.toString());
            int result = musicService.addAlbum(album);

            if (result > 0) {
                judge.setStatusCode(1);
                judge.setInfo("建立成功！");
            } else {
                judge.setStatusCode(-1);
                judge.setInfo("建立失败！");
            }
            return judge;
        } else {
            judge.setStatusCode(0);
            judge.setInfo("请选择正确图片文件！");
            return judge;
        }
    }


    @ApiOperation(value = "查找歌手全部专辑")
    @GetMapping("/queryallAlbof")
    public String queryallAlbof(Model model, int userId) {
        //歌手的热度增加+1
        musicService.addHotUser(userId);
        //通过Id获取歌手的专辑
        List<Album> list = musicService.queryallAlbof(userId);
        model.addAttribute("Musics", list);
        return "L-html/L-homepage/L-singer.html";
    }


    @ApiOperation(value = "查找歌手全部专辑和个人信息")
    @GetMapping("/queryall")
    public String queryall(Model model, int userId) {
        //歌手的热度增加+1
        musicService.addHotUser(userId);
        //获取专辑信息
        List<Album> list = musicService.queryallAlbof(userId);
        model.addAttribute("Musics", list);
        //获取个人信息
        List<Users> user = userService.queryByIdUser(userId);
        model.addAttribute("Users", user);
        return "L-html/L-homepage/L-singer.html";
    }


    @ApiOperation(value = "查询一个专辑内的所有歌曲")
    @GetMapping("/queryOneAlb")
    public String queryOneAlb(Model model, int albId, Integer page) {
        if (page == null) {
            page = 1;
        }
        //得到数据总数，算出总页数
        int count = 5;
        int sumPage = 0;
        if (count % 10 != 0) {
            sumPage = count / 10 + 1;
        } else {
            sumPage = count / 10;
        }
        //调用专辑热度+1
        musicService.addHotAlb(albId);
        List<Musics> list = musicService.queryOneAlb(albId);
        model.addAttribute("page", page);
        model.addAttribute("sumPage", sumPage);
        model.addAttribute("Musics", list);
        return "/L-html/L-homepage/L-allsonglist.html";
    }


    @ApiOperation(value = "删除一个专辑")
    @PostMapping("/deleteAlbum")
    @ResponseBody
    public Judge deleteAlbum(int albId, Model model) {
        //根据Id删除一个专辑
        int result = musicService.deleteAlbum(albId);
        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("删除成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("删除失败！");
        }
        return judge;
    }






    @ApiOperation(value = "删除一条评论")
    @PostMapping("/deleteDis")
    @ResponseBody
    public Judge deleteDis(int disId, Model model) {
        //根据ID删除评论
        int result = musicService.deleteDis(disId);
        if (result > 0) {
            judge.setStatusCode(1);
            judge.setInfo("删除成功！");
        } else {
            judge.setStatusCode(-1);
            judge.setInfo("删除失败！");
        }
        return judge;
    }

    @ApiOperation("查看歌曲评论")
    @GetMapping("/musicDis")
    public String musicDis(int mcId,Model model,HttpSession session){
        int likeCount = 0;
        Users user = (Users) session.getAttribute("USER");
        int userId = user.getUserId();
        List<Discuss> commentList = musicService.musicDiscuss(mcId);
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if(user!=null){
            if(commentVoList!=null){
                for(Discuss comment : commentList){
                    Map<String, Object> commentVo = new HashMap<>();
                    commentVo.put("comment", comment);
//                    likeStatus = musicService.discusslikestatus(userId);
//                    commentVo.put("likeCount",);
                }
            }
        }

        int num = musicService.totalDis(mcId);
        Albmusic album = musicService.queryByIdAlbmusic(mcId);
        Musics music = musicService.queryMusicById(mcId);
        Map<String,Integer> comment =new HashMap<String,Integer>();
        model.addAttribute("Music",music);
        model.addAttribute("AlbumMusic",album);
        model.addAttribute("total",num);
        return "/ypb/Y-html/Y-item/comment.html";
    }
}
